package com.ad.aidai.fragments.me.profile;

import android.content.Context;
import android.os.Bundle;
import android.view.View;

import com.ad.aidai.bean.ProfileBean;
import com.ad.aidai.bean.User;
import com.ad.aidai.common.ADApp;
import com.ad.aidai.common.RxBus;
import com.ad.aidai.common.listener.RecyclerViewListener;
import com.ad.aidai.common.utils.CheckUtil;
import com.ad.aidai.db.dao.MyUserDao;
import com.ad.aidai.events.CommonEvent;
import com.ad.aidai.network.ADUrl;
import com.ad.aidai.network.NetWork;
import com.ad.aidai.network.StatusCodeFromNet;
import com.ad.aidai.network.result.NetResult;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * LookProfilePresenter
 * <p>
 * Created by pure on 2017/1/12.
 */

public class ProfilePresenter implements ProfileContract.Presenter {

    private Context mContext;
    private ProfileContract.View mView;
    private CompositeSubscription mSubscriptions;
    private ProfileAdapter mAdapter;
    private List<ProfileBean> datas;

    public ProfilePresenter(Context context, ProfileContract.View view) {
        this.mContext = context;
        this.mView = view;
        mView.setPresenter(this);
        initData();
        mAdapter = new ProfileAdapter(context, datas);

        mAdapter.setOnItemClickListener(new RecyclerViewListener.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                ProfileBean bean = datas.get(position);
                if (bean.getType() != ProfileBean.VIEWTYPE_SPACE) {
                    checkClick(bean);
                }
            }

        });
        mAdapter.setOnItemLongClickListener(new RecyclerViewListener.OnRecyclerViewItemLongClickListener() {
            @Override
            public void onItemLongClick(View view, int position) {
                ProfileBean bean = datas.get(position);
                getCopyWord(bean);
            }
        });
    }

    private void initData() {
        datas = new ArrayList<>();
        datas.add(new ProfileBean(ProfileBean.VIEWTYPE_HEAD, "头像", ""));
        datas.add(new ProfileBean(ProfileBean.VIEWTYPE_STRING, "昵称", ""));
        datas.add(new ProfileBean(ProfileBean.VIEWTYPE_STRING, "性别", ""));
        datas.add(new ProfileBean());
        datas.add(new ProfileBean(ProfileBean.VIEWTYPE_STRING, "学校", "未绑定"));
        datas.add(new ProfileBean());
        datas.add(new ProfileBean(ProfileBean.VIEWTYPE_STRING, "手机", ""));
        datas.add(new ProfileBean(ProfileBean.VIEWTYPE_STRING, "支付宝", "未绑定"));
        datas.add(new ProfileBean());
        datas.add(new ProfileBean(ProfileBean.VIEWTYPE_STRING, "个性签名", ""));
    }

    private void getCopyWord(ProfileBean bean) {
        switch (bean.getName()) {
            case "学校":
                if (!bean.getValue().equals("未绑定")) {
                    mView.copyWord((String) bean.getValue());
                }
                break;
            case "支付宝":
                if (!bean.getValue().equals("未绑定")) {
                    mView.copyWord((String) bean.getValue());
                }
                break;
            case "个性签名":
                if (!bean.getValue().equals("未填写")) {
                    mView.copyWord((String) bean.getValue());
                }
                break;
            default:
                mView.copyWord((String) bean.getValue());
                break;
        }
    }

    private void checkClick(ProfileBean bean) {
        switch (bean.getName()) {
            case "头像":
                if (ADApp.getUser().getSchoolId() == null) {
                    mView.toast("请先绑定学校信息");
                    return;
                }
                mView.chooseHeadImage();
                break;
            case "昵称":
                Bundle bundleName = new Bundle();
                bundleName.putString("name", ADApp.getUser().getUserName());
                mView.modifyName(bundleName);
                break;
            case "性别":
                mView.selectSex();
                break;
            case "学校":
                if (bean.getValue().equals("未绑定")) {
                    mView.bindSchool();
                }
                break;
            case "学号":
                break;
            case "姓名":
                break;
            case "年级":
                break;
            case "手机":
                break;
            case "支付宝":
                Bundle bundlePayNum = new Bundle();
                bundlePayNum.putString("pay_num", ADApp.getUser().getUserPayNum());
                mView.modifyPayNum(bundlePayNum);
                break;
            case "个性签名":
                Bundle bundlePersonalNote = new Bundle();
                bundlePersonalNote.putString("personal_note", ADApp.getUser().getUserPersonalNote());
                mView.modifyPersonalNote(bundlePersonalNote);
                break;
        }
    }

    @Override
    public void loadUserData() {
        mView.setTitle("我的");
        User user = ADApp.getUser();
        Long schoolId = user.getSchoolId();
        if (schoolId == null) {
            schoolId = 0L;
        }

        String url = ADUrl.HEAD_ICON_URL.replace("{schoolId}", schoolId + "").replace("{photoName}", user.getUserIcon
                ());
        datas.get(0).setValue(url);
        datas.get(1).setValue(user.getUserName());
        datas.get(2).setValue(user.getUserSex() == 0 ? "男" : "女");
        datas.get(6).setValue(user.getUserTel());
        String payNum = user.getUserPayNum();
        if (CheckUtil.checkStrNull(payNum)) {
            payNum = "未绑定";
        }
        datas.get(7).setValue(payNum);
        String note = user.getUserPersonalNote();
        if (CheckUtil.checkStrNull(note)) {
            note = "太懒了，什么都不写!";
        }
        datas.get(9).setValue(note);

        if (!CheckUtil.checkStrNull(user.getSchoolName())) {
            datas.get(4).setValue(user.getSchoolName());
            datas.add(5, new ProfileBean(ProfileBean.VIEWTYPE_STRING, "学号", user.getUserStuNumber()));
            datas.add(6, new ProfileBean(ProfileBean.VIEWTYPE_STRING, "姓名", user.getUserRealName()));
            datas.add(7, new ProfileBean(ProfileBean.VIEWTYPE_STRING, "年级", user.getUserGrade()));
        }

        mAdapter.notifyItemRangeChanged(0, datas.size());
    }

    @Override
    public void userBindSchool() {
        User user = ADApp.getUser();
        if (!CheckUtil.checkStrNull(user.getSchoolName())) {
            datas.get(4).setValue(user.getSchoolName());
            mAdapter.notifyItemChanged(4);
            datas.add(5, new ProfileBean(ProfileBean.VIEWTYPE_STRING, "学号", user.getUserStuNumber()));
            mAdapter.notifyItemInserted(5);
            datas.add(6, new ProfileBean(ProfileBean.VIEWTYPE_STRING, "姓名", user.getUserRealName()));
            mAdapter.notifyItemInserted(6);
            datas.add(7, new ProfileBean(ProfileBean.VIEWTYPE_STRING, "年级", user.getUserGrade()));
            mAdapter.notifyItemInserted(7);
        }
    }

    @Override
    public void userModifyPayNum() {
        User user = ADApp.getUser();
        String payNum = user.getUserPayNum();
        if (CheckUtil.checkStrNull(payNum)) {
            payNum = "未绑定";
        }
        if (ADApp.getUser().getSchoolId() == null) {
            datas.get(7).setValue(payNum);
            mAdapter.notifyItemChanged(7);
        } else {
            datas.get(10).setValue(payNum);
            mAdapter.notifyItemChanged(10);
        }
    }

    @Override
    public void userModifyPersonalNote() {
        User user = ADApp.getUser();
        String note = user.getUserPersonalNote();
        if (CheckUtil.checkStrNull(note)) {
            note = "太懒了，什么都不写!";
        }
        if (ADApp.getUser().getSchoolId() == null) {
            datas.get(9).setValue(note);
            mAdapter.notifyItemChanged(9);
        } else {
            datas.get(12).setValue(note);
            mAdapter.notifyItemChanged(12);
        }

    }

    @Override
    public void userChangeHead() {
        User user = ADApp.getUser();
        String url = ADUrl.HEAD_ICON_URL.replace("{schoolId}", user.getSchoolId() + "").replace("{photoName}", user
                .getUserIcon());
        datas.get(0).setValue(url);
        mAdapter.notifyItemChanged(0);
    }

    @Override
    public void userChangeSex(final int sex) {

        mView.showLoading("修改");
        NetWork.getAccountOperationApi()
                .updateUserSex(ADApp.getUser().getUserId(), sex)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NetResult>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        MobclickAgent.reportError(mContext, e);
                        Logger.t("updateUserSex").e(e.getMessage());
                        //关闭加载对话框
                        mView.closeLoading(false);
                    }

                    @Override
                    public void onNext(NetResult netResult) {
                        if (netResult.getCode() != StatusCodeFromNet.CODE_SUCCESS) {
                            Logger.t("updateUserSex").e(netResult.toString());
                            mView.closeLoading(false);
                        } else {
                            Logger.t("updateUserSex").i("updateUserSex:" + sex);
                            User user = ADApp.getUser();
                            user.setUserSex(sex);
                            datas.get(2).setValue(sex == 0 ? "男" : "女");
                            mAdapter.notifyItemChanged(2);
                            MyUserDao.getUserDao().save(user);
                            RxBus.getInstance().postEvent(new CommonEvent(CommonEvent.USER_SEX));
                            mView.closeLoading(true);
                        }
                    }
                });
    }

    @Override
    public ProfileAdapter getAdapter() {
        return mAdapter;
    }

    @Override
    public void userModifyName() {
        User user = ADApp.getUser();
        datas.get(1).setValue(user.getUserName());
        mAdapter.notifyItemChanged(1);
    }

    @Override
    public void subscribe() {
        mSubscriptions = new CompositeSubscription();
    }

    @Override
    public void unSubscribe() {
        mContext = null;
        mView = null;
        mSubscriptions.clear();
    }

    @Override
    public void uploadHead(String path) {

        mView.showLoading("上传");

        if (CheckUtil.checkStrNull(path)) {
            mView.closeLoading(false);
            return;
        }
        long currentTime = System.currentTimeMillis();
        final String fileName = getDateToString(currentTime) + ".jpg";

        File file = new File(path);
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("fileData", fileName, requestFile);

        long userId = ADApp.getUser().getUserId();
        long schoolId = 0;
        if (ADApp.getUser().getSchoolId() != null) {
            schoolId = ADApp.getUser().getSchoolId();
        }

        Logger.t("LookProfilePresenter").i("fileName:" + fileName + "---file.getName():" + file.getName());

        Map<String, String> maps = new HashMap<>();
        maps.put("userId", userId + "");
        maps.put("schoolId", schoolId + "");
        maps.put("userIcon", fileName);

        NetWork.getAccountOperationApi()
                .updateUserIcon(maps, part)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NetResult>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        MobclickAgent.reportError(mContext, e);
                        Logger.t("LookProfilePresenter").e(e.getMessage());
                        //关闭加载对话框
                        mView.closeLoading(false);
                    }

                    @Override
                    public void onNext(NetResult netResult) {
                        if (netResult.getCode() != StatusCodeFromNet.CODE_SUCCESS) {
                            Logger.t("LookProfilePresenter").e(netResult.toString());
                            mView.closeLoading(false);
                        } else {
                            Logger.t("LookProfilePresenter").i("userIcon:" + fileName);
                            ADApp.getUser().setUserIcon(fileName);
                            MyUserDao.getUserDao().save(ADApp.getUser());
                            userChangeHead();
                            RxBus.getInstance().postEvent(new CommonEvent<>(CommonEvent.USER_HEAD_CHANGE, fileName));
                            mView.closeLoading(true);
                        }
                    }
                });

    }

    private String getDateToString(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        Date d = new Date(time);
        return sf.format(d);
    }
}
